import {
  InspectionApi
} from "../../common/apis/inspection";
import {
  createStoreBindings
} from "mobx-miniprogram-bindings";
import {
  INSPECTION_RECTIFY_STATUS_MAP,
  INSPECTION_RESULT,
  INSPECTION_HANDLE_METHOD
} from '../../config/inspection.config'
import {
  SUB_PAGES
} from '../../config/router.config'
import {
  inspectionTaskIndexDetailStore
} from "../../store/inspectionTaskIndexDetailStore";
import {
  WxValidate
} from "../../utils/WxValidate";
import {
  userSelectStore
} from "../../store/userSelectStore";
import {
  getCurrentPage,
  toDeptSelectPage,
  toDicSelectPage,
  toUserSelectPage
} from "../../utils/util";
import {
  DIC_KEY
} from "../../config/dicKey.config";
import {
  dicSelectStore
} from "../../store/dicSelectStore";
import {
  deptSelectStore
} from "../../store/deptSelectStore";
import {
  getDicList
} from "../../utils/dic";
const mixin_formItemType = require('../../common/mixins/formItemType')
const mixin_dicKey = require('../../common/mixins/dicKey')

Page({
  behaviors: [mixin_formItemType, mixin_dicKey],

  /** 
   * 页面的初始数据
   */
  data: {
    //  预计工时单位
    timeUnit: '小时',
    detailData: {
      taskItemList: [{
        measuredValue: 1,
        rectifyOpinion: 'xxxxx',
        result: 1,
        itemUnitToName: '&'
      }]
    },
    // 整改状态 ,默认已整改
    state: '1',
    INSPECTION_RECTIFY_STATUS_MAP,
    INSPECTION_RESULT,
    INSPECTION_HANDLE_METHOD,
    // 指派科室列表
    deptList: [{
      label: '多选',
      value: 'checkbox1'
    }, ],
    // 响应类型
    responseTypeList: getDicList(DIC_KEY.obs_fault_response),
    appointmentVisible: false,
    // 时间选择组件回显值
    dateTimePickerValue: Date.now(),
  },
  // 责任人选择
  choseUser() {
    toUserSelectPage(SUB_PAGES.Inspection.INSPECTION_TASK_INDEX_DETAIL.router, 'inspectionTaskRectifyUserValue', false)

  },
  // 转交
  onTransfer() {

  },

  // 去处理
  onHandle() {
    wx.navigateTo({
      url: `${SUB_PAGES.Inspection.RECTIFICATION_INDEX_HANDLE.router}?id=${this.data.detailData?.id || ''}`
    })
  },

  initData(id) {
    const self = this
    InspectionApi.getInspectionHistoryDetail(id, (res) => {
      console.log(res);
      self.setData({
        detailData: res.data
      })
    })
  },

  submit() {
    const {
      elaborate,
      handleMethod,
      inspectionPhotos,
      inspectionSound,
      orderAddDto,
      rectifyEndDate,
      rectifyOpinion,
      rectifyStartDate,
      rectifyUserId,
      result,
      soundFile,
      taskItemList,
    } = this.data
    const formData = {
      elaborate,
      handleMethod,
      inspectionPhotos,
      inspectionSound,
      orderAddDto,
      rectifyEndDate,
      rectifyOpinion,
      rectifyStartDate,
      rectifyUserId,
      result,
      soundFile,
      taskItemList,
    }
    const rules = {
      inspectionPhotos: {
        required: false,
        inspectionPhotos: true
      },
      rectifyStartDate: {
        required: false,
        rectifyStartDate: true
      },
      rectifyUserId: {
        required: false,
        rectifyUserId: true
      },
    }
    const validate = new WxValidate(rules, {})
    // 自定义验证规则
    validate.addMethod('inspectionPhotos', (value, param) => {
      /**
       * 巡检结果 - 正常/异常
       * 必填
       * 巡检过程照片
       */
      if ([1, 2].includes(result)) {
        return Boolean(value.length)
      }
      return true
    }, '请上传巡检过程照片')
    /**
     * 巡检结果 - 异常/限期整改
     * 必填
     * 整改日期
     * 整改责任人
     */
    if (result == 2 && handleMethod == 1) {
      validate.addMethod('rectifyStartDate', (value, param) => {
        return value != ''
      }, '请选择整改日期')
      validate.addMethod('rectifyUserId', (value, param) => {
        return rectifyUserId != ''
      }, '请选择整改责任人')
    }



    // 传入表单数据，调用验证方法
    if (!validate.checkForm(formData)) {
      const error = validate.errorList[0]
      wx.showToast({
        icon: 'none',
        title: error.msg,
      })
      return
    }
    /**
     * 巡检结果 - 异常/转工单
     * 必填
     * 创建时间
     * 故障描述
     * 故障分类
     * 指派科室
     */
    if (result == 2 && handleMethod == 2) {
      let msg = ''
      if (orderAddDto.faultRemark.trim() == '') {
        msg = '故障描述不能为空'
      } else if (!orderAddDto.faultType) {
        msg = '请选择故障分类'
      }
      if (msg) {
        wx.showToast({
          icon: 'none',
          title: msg,
        })
        return
      }
    }
    InspectionApi.inspectionTaskHandle(formData, () => {

    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {
      id,
      state
    } = options
    this.setData({
      state: state
    })
    this.initData(id)
    this.storeBindings = createStoreBindings(this, {
      store: inspectionTaskIndexDetailStore,
      fields: ['elaborate', , 'handleMethod', 'inspectionPhotos', 'inspectionSound', 'orderAddDto', 'rectifyEndDate', 'rectifyOpinion', 'rectifyStartDate', 'rectifyUserId', 'result', 'soundFile', 'taskItemList', ],

      actions: ['inspectionTaskIndexDetailStoreRest', 'setResult', 'setHandleMethod', 'setInspectionPhotos', 'setRectifyDate', 'inspectionTaskRectifyUserValue', 'setRectifyUserId', 'setOrderAddDtoCreateTime', 'setOrderFaultRemark', 'setOrderFaultType', 'setOrderRecording', 'setOrderEnclosure', 'setOrderSendType', 'setOrderChangeDept', 'setOrderDeptId', 'changeOrderTag', 'setOrderAppointment', 'setOrderResponseType', 'setOrderEquimentAddress', 'setOrderPlace', 'setOrderReqTime', ''],
    });
    this.storeBindings1 = createStoreBindings(this, {
      store: userSelectStore,
      fields: ['inspectionTaskRectifyUserValue'],
      actions: [],
    });
    this.storeBindings2 = createStoreBindings(this, {
      store: dicSelectStore,
      fields: ['inspectionTaskToOrderFaultTypeValue', 'inspectionTaskToOrderPlaceValue'],
      actions: [],
    });
    this.storeBindings3 = createStoreBindings(this, {
      store: deptSelectStore,
      fields: ['inspectionToOrderReportDepValue', 'inspectionToOrderEquimentAddressValue'],
      actions: [],
    });



    this.storeBindings.updateStoreBindings()
    this.storeBindings1.updateStoreBindings()
    this.storeBindings2.updateStoreBindings()
    this.storeBindings3.updateStoreBindings()


    this.setRectifyUserId(this.data.inspectionTaskRectifyUserValue)
    this.setOrderFaultType(this.data.inspectionTaskToOrderFaultTypeValue)
    this.setOrderDeptId(this.data.inspectionToOrderReportDepValue)
    this.setOrderEquimentAddress(this.data.inspectionToOrderEquimentAddressValue)
    this.setOrderPlace(this.data.inspectionTaskToOrderPlaceValue)
  },

  changeResult(e) {
    this.setResult(e.detail.value)
  },
  changeMethod(e) {
    this.setHandleMethod(e.detail.value)
  },
  onPhoto(e) {
    this.setInspectionPhotos(e.detail.value)
  },
  // 选择故障分类
  choseFaultType() {
    toDicSelectPage(getCurrentPage(), 'inspectionTaskToOrderFaultTypeValue', DIC_KEY.obs_fault_type, false)
  },
  // 选择实际报修地址
  chosePlace() {
    toDicSelectPage(getCurrentPage(), 'inspectionTaskToOrderPlaceValue', DIC_KEY.obs_repair_place, false)
  },
  // 资产位置
  choseEquipment() {
    toDeptSelectPage(getCurrentPage(), 'inspectionToOrderEquimentAddressValue', 'selectDept', false)
  },

  // 报修科室选择 
  choseReportDept() {
    toDeptSelectPage(getCurrentPage(), 'inspectionToOrderReportDepValue', 'selectDept', false)
  },

  // 选择预约时间
  onSelectAppointment() {
    this.setData({
      appointmentVisible: true
    })
  },
  // 时间确认按钮
  onConfirmTime(e) {

    this.setOrderAppointment(e.detail.value)
  },
  // 时间取消按钮
  onCancelTime() {
    this.setData({
      datetimeVisible: false
    })
  },

  onSelectTimeUint() {
    const units = ['小时', '分钟']
    const self = this
    wx.showActionSheet({
      itemList: units,
      success({
        tapIndex
      }) {
        self.setData({
          timeUnit: units[tapIndex]
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.storeBindings.destroyStoreBindings()
    this.storeBindings1.destroyStoreBindings()
    this.storeBindings2.destroyStoreBindings()
    this.storeBindings3.destroyStoreBindings()



  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})